import 'babel-polyfill';  // 兼容浏览器执行生成器函数 
// effects 处理副作用的微任务actions 
// put 就相当于 dispatch(action)
import {takeEvery,all,call,put,take} from 'redux-saga/effects';
import * as types from './store/action-types';
// push Redirect跳转路由(action) ——> put执行action
import {push} from 'react-router-redux';
// sleep(ms)就是这么实现的
export const delay = ms => new Promise(function(resolve){
  setTimeout(() => {
    resolve();
  }, ms);
})
/**
 * saga 管理所有的action: 也就是generate function
 */
let Api = {
  login(username,password){
      return new Promise(function(resolve,reject){
         //setTimeout(function(){
          resolve(username+password);
          console.log('login resolve');
        // },1000);
      });
  }
}
function* login(username,password){
  try{
    //命令saga中间件立即调用 Api.login(username, password) 
    // 返回action = {type: 'call', fn: Api.login, args:[username, password]} 
    // 方便调试
    let token = yield call(Api.login,username,password);
    //let token = yield Api.login(username,password);

    console.log('token',token);
    yield put({type:types.LOGIN_SUCCESS,token});
    //跳到个人页
    yield put(push('/logout')); 
    return token;
  }catch(error){
    put({type:types.LOGIN_ERROR,error});
  }
}
function* loginFlow(){
  while(true){
     let {username,password} = yield take(types.LOGIN_REQUEST);
     let token = yield login(username,password);
     if(token){
       yield take(types.LOGOUT_REQUEST);
       //跳回登录
       yield put(push('/login')); 
     }
  }
}

function* watchAction(getState){
  // 监听特定的action-type：接收一个操作action
  yield takeEvery('*', function* (action){
    console.log(getState());
    console.log(action);
  }, args=dispatch); // args会传递给监听action
}

// 管理action：监听与派发执行
export function* rootSaga({getState}){
  // yield all 相当于 Promise.All
  yield all([loginFlow(),watchAction(getState)]);
} 